package org.linlinjava.litemall.wx.web;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.QrCodeUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallDisputeOrder;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.domain.NewsPay;
import org.linlinjava.litemall.db.service.LitemallDisputeService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.NewsPayService;
import org.linlinjava.litemall.db.util.DisputeConstant;
import org.linlinjava.litemall.db.util.OrderConstant;
import org.linlinjava.litemall.wx.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * @description: 支付模块
 * @program: mall
 * @author: youvy 永辉
 * @create: 2019-11-23 20:46
 **/
@RestController
@RequestMapping("/wx/pay")
public class WxPayController {
	private final Log logger = LogFactory.getLog(WxPayController.class);
	private String path = "/home/QRImage/";
	private String pathNews = "/home/QRImage/news/";
	private String pathMargin="/home/QRImage/Margin/";
	//String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode"+File.separator;
	@Autowired
	private PayService payService;
	@Autowired
	private StorageService storageService;
	@Autowired
	private LitemallOrderService orderService;
	@Autowired
	private NewsPayService newsPayService;
	@Autowired
	private LitemallDisputeService disputeService;

	/**
	 * nativePay微信支付
	 * @param body  orderId订单编号
	 * @param request 获取用户信息
	 * @return
	 */
	@PostMapping("nativePay")
	public Object nativePay(@RequestBody String body, HttpServletRequest request) throws FileNotFoundException {
		Integer orderId = JacksonUtil.parseInteger(body, "orderId");
		XxlSsoUser currentUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
		if (currentUser == null) {
			return ResponseUtil.unauthz();
		}
		String userId = currentUser.getUserid();
		String url = payService.nativePay(Integer.valueOf(userId), body, request).toString();
		if (!url.contains("weixin")){
			return ResponseUtil.fail(801,"微信支付订单生成错误");
		}
		//查找订单的  实际支付金额
		BigDecimal actualPrice = orderService.findById(orderId).getActualPrice();

		//2020.05月魏来新加   不能超过的数额   1000元拦截 弹出
		BigDecimal exceed = new BigDecimal("1000.00");
		if(actualPrice.compareTo(exceed) >= 0 ){
			return ResponseUtil.fail(402,"大于1000的额度,请走对公转账");
		}
		QrCodeUtil.createQrCode(url,path,orderId+".jpg");
		File file = new File(path+orderId+".jpg");
		FileInputStream inputStream = new FileInputStream(file);
		//存储分享图
		LitemallStorage litemallStorage = storageService.store(inputStream, file.length(), "image/jpeg",
				getKeyName("order_"+orderId+""));
		return ResponseUtil.ok(litemallStorage.getUrl());
	}

    /**
     *  微信支付 信息
     * @param body  id
     * @param request
     * @return
     * @throws FileNotFoundException
     */
	@PostMapping("nativePayNews")
	public Object nativePayNews(@RequestBody String body, HttpServletRequest request) throws FileNotFoundException {
		Integer id = JacksonUtil.parseInteger(body, "id");
		XxlSsoUser currentUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
/*		if (currentUser == null) {
			return ResponseUtil.unauthz();
		}*/
		String userId = currentUser.getUserid();
		//Integer userId = JacksonUtil.parseInteger(body, "userId");
		String url = payService.nativePayNews(Integer.valueOf(userId), body, request).toString();
		if (!url.contains("weixin")){
			return ResponseUtil.fail(801,"微信支付订单生成错误");
		}
		QrCodeUtil.createQrCode(url,pathNews,id+".jpg");
		File file = new File(pathNews+id+".jpg");
		FileInputStream inputStream = new FileInputStream(file);
		//存储分享图
		LitemallStorage litemallStorage = storageService.store(inputStream, file.length(), "image/jpeg",
				getKeyName("news_"+id));
		return ResponseUtil.ok(litemallStorage.getUrl());
	}

	//支付保证金
	@PostMapping("nativePayMargin")
	public Object nativePayMargin(@RequestBody String body, HttpServletRequest request) throws FileNotFoundException {
		Integer id = JacksonUtil.parseInteger(body, "id");
		XxlSsoUser currentUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
/*		if (currentUser == null) {
			return ResponseUtil.unauthz();
		}*/
		String userId = currentUser.getUserid();
		//Integer userId = JacksonUtil.parseInteger(body, "userId");
		String url = payService.nativePayMargin(Integer.valueOf(userId), body, request).toString();
		if (!url.contains("weixin")){
			return ResponseUtil.fail(801,"微信支付订单生成错误");
		}
		QrCodeUtil.createQrCode(url,pathMargin,id+".jpg");
		File file = new File(pathMargin+id+".jpg");
		FileInputStream inputStream = new FileInputStream(file);
		//存储分享图
		LitemallStorage litemallStorage = storageService.store(inputStream, file.length(), "image/jpeg",
				getKeyName("margin_"+id));
		return ResponseUtil.ok(litemallStorage.getUrl());
	}
	private String getKeyName(String orderId) {
		return "GOOD_QCODE_" + orderId + ".jpg";
	}

	/**
	 * 微信付款成功或失败回调接口
	 * <p>
	 * TODO
	 * 注意，这里pay-notify是示例地址，建议开发者应该设立一个隐蔽的回调地址
	 *
	 * @param request  请求内容
	 * @param response 响应内容
	 * @return 操作结果
	 */
	@PostMapping("shuanglin-notify")
	public Object payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return payService.payNotify(request, response);
	}

	@PostMapping("orderPayQuery")
	public Object orderPayQuery(@RequestBody String body, HttpServletRequest request){
		Integer orderId = JacksonUtil.parseInteger(body, "orderId");
/*		XxlSsoUser currentUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
		if (currentUser == null) {
			return ResponseUtil.unauthz();
		}
		String userId = currentUser.getUserid();*/
		LitemallOrder order = orderService.findById(orderId);
		if (order.getOrderStatus().shortValue()== OrderConstant.PAYED) {
			return ResponseUtil.ok("订单支付成功",802);
		}
		return ResponseUtil.fail(803,"订单支付失败");
	}

	@PostMapping("/bankPay")
	public Object bankPay(HttpServletRequest request, @RequestParam(value = "file")MultipartFile file,
						  @RequestParam String msg) {
		XxlSsoUser currentUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
		if (currentUser == null) {
			return ResponseUtil.unauthz();
		}
		String userId = currentUser.getUserid();
		Integer orderId = JacksonUtil.parseInteger(msg, "id");
		if (StringUtils.isEmpty(path) || orderId == null) {
			return ResponseUtil.badArgument();
		}
		LitemallOrder order = orderService.findById(orderId);
		if (!order.getUserId().toString().equals(userId)) {
			return ResponseUtil.unauthz();
		}
		if (!order.getOrderStatus().equals(OrderConstant.CONFIRMED)) {
			return ResponseUtil.badArgumentValue();
		}
		return saveFile(file, request, order);
	}

    /**
     * 银行支付保证金
     * @param request
     * @param file   需要上传对公账户的凭证
     * @param msg  id是订单orderId
     * @return
     */
	@PostMapping("/bankPayMargin")
	public Object bankPayMargin(HttpServletRequest request, @RequestParam(value = "file")MultipartFile file,
								@RequestParam String msg) {
		XxlSsoUser currentUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
		if (currentUser == null) {
			return ResponseUtil.unauthz();
		}
		String userId = currentUser.getUserid();
		Integer orderId = JacksonUtil.parseInteger(msg, "id");
		if (StringUtils.isEmpty(path) || orderId == null) {
			return ResponseUtil.badArgument();
		}
		//争议订单
		LitemallDisputeOrder order = disputeService.findOrderById(orderId);
		if (!order.getUserId().toString().equals(userId)) {
			return ResponseUtil.unauthz();
		}
		if (!order.getState().equals(DisputeConstant.WAIT_PAYING)) {
			return ResponseUtil.badArgumentValue();
		}
		return saveFile(file, request, order);
	}

    /**
     * 查询付款  : newsPayService  可能是 查询行业新闻的付款..如果不确定问永辉
     * @param json   id
     * @param request
     * @return
     */
	@PostMapping("/queryPay")
	public Object queryPay(@RequestBody String json,HttpServletRequest request){
		XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
		Integer userId = Integer.parseInt(user.getUserid());
		Integer id = JacksonUtil.parseInteger(json, "id");
		NewsPay newsPay = newsPayService.findByNewsId(id, userId);
		if (newsPay!=null){
			return ResponseUtil.ok(newsPay.getPayStatus());
		}else {
			return ResponseUtil.ok(0);
		}
	}

    /**
     *  保存文件..源文件:两个saveFile. 但是不一样..一个是订单的..一个是争议单的..不要删除下边的
     * @param file  保存文件
     * @param request  请求
     * @param order  订单内容
     * @return
     */
	private Object saveFile(MultipartFile file, HttpServletRequest request, LitemallOrder order) {
		try {
			request.setCharacterEncoding("utf-8");
			if (file != null) {
				String originalFilename = file.getOriginalFilename();
				String type = originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1) : null;
				if (type != null) {
					String name = "bank_" + System.currentTimeMillis() + "_" + new Random().nextInt() + "." + type;
					String realPath = System.getProperty("user.dir");
					String path = realPath + "/bankPay/" + name;
					File dir = new File(realPath + "/bankPay");
					if (!dir.exists()) {
						dir.mkdirs();
					}
					file.transferTo(new File(path));
					order.setOrderStatus(OrderConstant.PAYING);
					order.setPayCreateTime(LocalDateTime.now());
					order.setPayCertificate(name);
					orderService.updateWithOptimisticLocker(order);
					return ResponseUtil.ok();
				}
			}
			return ResponseUtil.fail(403, "未取到合法文件");
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.fail(500, e.toString());
		}
	}

	private Object saveFile(MultipartFile file, HttpServletRequest request, LitemallDisputeOrder order) {
		try {
			request.setCharacterEncoding("utf-8");
			if (file != null) {
				String originalFilename = file.getOriginalFilename();
				String type = originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1) : null;
				if (type != null) {
					String name = "bank_" + System.currentTimeMillis() + "_" + new Random().nextInt() + "." + type;
					String realPath = System.getProperty("user.dir");
					String path = realPath + "/bankPay/" + name;
					File dir = new File(realPath + "/bankPay");
					if (!dir.exists()) {
						dir.mkdirs();
					}
					file.transferTo(new File(path));
					order.setState(DisputeConstant.RECHECKING);
					order.setPayTime(LocalDateTime.now());
					order.setPayId(name);
					disputeService.updateWithOptimisticLocker(order);
					return ResponseUtil.ok();
				}
			}
			return ResponseUtil.fail(403, "未取到合法文件");
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.fail(500, e.toString());
		}
	}
}
